package org.example.chatservice.service;

import lombok.RequiredArgsConstructor;
import org.example.chatservice.entity.ChatMessage;
import org.example.chatservice.entity.ChatRoom;
import org.example.chatservice.repository.ChatMessageRepository;
import org.example.chatservice.repository.ChatRoomRepository;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

@Service
@RequiredArgsConstructor
public class ChatService {
    private final SimpMessagingTemplate messagingTemplate;
    private final ChatMessageRepository messageRepository;
    private final ChatRoomRepository chatRoomRepository;

    public void sendPrivateMessage(ChatMessage message) {
        message.setTimestamp(LocalDateTime.now());
        message.setRead(false);
        
        // 获取或创建私聊房间
        ChatRoom chatRoom = getChatRoomForUsers(message.getSenderId(), message.getReceiverId());
        message.setConversationId(chatRoom.getId());
        
        // 保存消息
        messageRepository.save(message);
        
        // 发送消息到指定用户
        messagingTemplate.convertAndSendToUser(
            message.getReceiverId(),
            "/queue/messages",
            message
        );
    }

    public void sendGroupMessage(ChatMessage message) {
        message.setTimestamp(LocalDateTime.now());
        messageRepository.save(message);
        
        // 发送消息到群组
        messagingTemplate.convertAndSend(
            "/topic/group/" + message.getReceiverId(),
            message
        );
    }

    public ChatRoom createGroupChatRoom(String name, String creatorId, List<String> participants) {
        ChatRoom chatRoom = new ChatRoom();
        chatRoom.setName(name);
        chatRoom.setCreatorId(creatorId);
        chatRoom.setType(ChatRoom.ChatType.GROUP);
        chatRoom.setCreatedAt(LocalDateTime.now());
        chatRoom.getParticipants().addAll(participants);
        chatRoom.getParticipants().add(creatorId);
        
        return chatRoomRepository.save(chatRoom);
    }

    private ChatRoom getChatRoomForUsers(String user1Id, String user2Id) {
        // 查找现有的私聊房间
        Optional<ChatRoom> existingRoom = chatRoomRepository.findPrivateRoom(user1Id, user2Id);
        
        if (existingRoom.isPresent()) {
            return existingRoom.get();
        }

        // 创建新的私聊房间
        ChatRoom newRoom = new ChatRoom();
        newRoom.setType(ChatRoom.ChatType.PRIVATE);
        newRoom.setCreatedAt(LocalDateTime.now());
        newRoom.getParticipants().add(user1Id);
        newRoom.getParticipants().add(user2Id);
        
        return chatRoomRepository.save(newRoom);
    }

    public List<ChatMessage> getConversationHistory(String conversationId) {
        return messageRepository.findByConversationIdOrderByTimestampDesc(conversationId);
    }

    public List<ChatRoom> getUserChatRooms(String userId) {
        return chatRoomRepository.findByParticipantsContaining(userId);
    }

    public void markMessagesAsRead(String conversationId, String userId) {
        messageRepository.markMessagesAsRead(conversationId, userId);
    }
}